//Alert manager
var msgStack = [];                    // Array Of All Alerts
var MSGtop;                           // Message That Was On Top During An Animation
var MSGbottom;                        // Message That Was Below During An Animation
var diff = 0;                         // The Current Differnce Between The Stack And Currently Displayed Alert
var alertWidth = "-100%";             // Negative Width Of The Alert Div
var defaultMsg = "Welcome To Crombz!";// First Shown Message (diff==0)

// Creates A Event Listener So The User Can View All Of The Alerts Using The backAnAlert Function
$(document).ready(function(){
        $('#Alert').on("swipeleft",function(){backAnAlert()})
        $('#Alert').on("swiperight",function(){fowardAnAlert()})
        makeAlert(defaultMsg);
});

// Animates An Alert In
function makeAlert(msg){
        msgStack.push(msg)
        $('#dummyAlert').css({left:alertWidth})
        $('#dummyMSG').text(msg)
        $('#dummyAlertCounter').text(msgStack.length)
        $('#dummyAlert').animate({
                left:'0px',
                opacity:1
        },800,function(){
                $('#MSG').text(msg)
                $('#alertCounter').text(msgStack.length)
                $('#dummyAlert').css({left:alertWidth,opacity:'0'})
        })
}
// Goes Back One Alert In The Stack (diff+1)
function backAnAlert(){
	if(msgStack.length !== 1){
        diff++
        if(diff==msgStack.length){
                diff=0
                $('#dummyAlert').css({left:alertWidth})
                MSGtop = $('#MSG').text()
                $('#dummyMSG').text(MSGtop)
                $('#dummyAlertCounter').text(1)
                $('#dummyAlert').css({left:'0px',opacity:1})
                MSGbottom = msgStack[(msgStack.length-diff)-1]
                $('#MSG').text(MSGbottom)
                $('#alertCounter').text(msgStack.length-diff)
                $('#dummyAlert').animate({
                        left:alertWidth,
                        opacity:0
                },800,false)
        }else{
                $('#dummyAlert').css({left:alertWidth})
                MSGtop = $('#MSG').text()
                $('#dummyMSG').text(MSGtop)
                $('#dummyAlertCounter').text((msgStack.length-(diff-1)))
                $('#dummyAlert').css({left:'0px',opacity:1})
                MSGbottom = msgStack[(msgStack.length-diff)-1]
                $('#MSG').text(MSGbottom)
                $('#alertCounter').text(msgStack.length-diff)
                $('#dummyAlert').animate({
                        left:alertWidth,
                        opacity:0
                },800,false)
        }
 	}
}

// Go Foward An Alert In The Stack (diff-1)
function fowardAnAlert(){
	if(msgStack.length !== 1){
        diff--
        if(diff==-1){
                diff=(msgStack.length)-1
                $('#dummyAlert').css({left:alertWidth})
                $('#dummyMSG').text(msgStack[0])
                $('#dummyAlertCounter').text("1")
                $('#dummyAlert').animate({
                        left:'0px',
                        opacity:1
                },800,function(){
                        $('#MSG').text(msgStack[0])
                        $('#alertCounter').text("1")
                        $('#dummyAlert').css({left:alertWidth,opacity:'0'})
                })
        }else{
                $('#dummyAlert').css({left:alertWidth})
                $('#dummyMSG').text(msgStack[(msgStack.length-diff)-1])
                $('#dummyAlertCounter').text((msgStack.length-diff))
                $('#dummyAlert').animate({
                        left:'0px',
                        opacity:1
                },800,function(){
                        $('#MSG').text(msgStack[(msgStack.length-diff)-1])
                        $('#alertCounter').text((msgStack.length-diff))
                        $('#dummyAlert').css({left:alertWidth,opacity:'0'})
                })
        }
	}
}

// DEBUGGING! Only Have 1 Block Running At A Time!
// ***********************************************

// setInterval(function(){makeAlert("This Is An Alert")},1500,false)



/*
$(document).ready(function(){
$('#widgets').html(($('#widgets').html())+"<button id='make'>Make Alert</button><textarea id='alertValue'></textarea><button id='back'>Go Back!</button>")
$('#make').click(function(){makeAlert($('#alertValue').val())});
$('#back').click(function(){backAnAlert()});
});
*/



/*
makeAlert("1")
makeAlert("2")
makeAlert("3")
makeAlert("4")
makeAlert("5")
*/

// ************************************************

var tapStatus = "free";
var isImage=false;

function setFunctions(id,displayTitle,icon,action,update,ontap,dts){
	if(update!==0){
		action=parseFunction(action,id);
		setInterval(function(){eval(action)},update,false);
	}
	ontap=parseFunction(ontap,id);
	if(dts==true){
		shiftPX = "30px";
	} else {
		shiftPX = "25px";
	}
	$("#"+id).append("<span id='TITLE"+id+"' style='margin-top:"+shiftPX+";'>"+displayTitle+"</span>");
	if(isImage){
		$("#TITLE"+id).css({"float":"right","margin-top":"61px","margin-right":"5px","display":"inline-block"});
	}
	$("#TITLE"+id).css("opacity","0");
	$('#'+id).click(function(){
		if(tapStatus=="free"){
			tapStatus = id;
			console.log("OPEN FROM FREE "+tapStatus);
			$("#"+id).addClass("widgetLong");
			$("#"+id).removeClass("widgetShort");
			$("#IMG"+id).addClass("widgetIMGlong");
			$("#IMG"+id).removeClass("widgetIMGshort");
			
			$("#TITLE"+id).css("opacity","1");
		} else if(tapStatus!==id){
			console.log("CLOSE "+tapStatus);

			$("#TITLE"+tapStatus).css("opacity","0");
			
			$("#"+tapStatus).removeClass("widgetLong");
			$("#"+tapStatus).addClass("widgetShort");
			$("#IMG"+tapStatus).removeClass("widgetIMGlong");
			$("#IMG"+tapStatus).addClass("widgetIMGshort");
			
			$("#"+id).addClass("widgetLong");
			$("#"+id).removeClass("widgetShort");
			$("#IMG"+id).addClass("widgetIMGlong");
			$("#IMG"+id).removeClass("widgetIMGshort");
			
			$("#TITLE"+id).css("opacity","1");
			tapStatus = id;
		} else {
			console.log("CLOSE SELF "+tapStatus);
			$("#TITLE"+id).css("opacity","0");
			
			$("#"+id).removeClass("widgetLong");
			$("#"+id).addClass("widgetShort");
			$("#IMG"+id).removeClass("widgetIMGlong");
			$("#IMG"+id).addClass("widgetIMGshort");
			tapStatus = "free";
		}
		$('#'+id).css({"box-shadow":"inset 0 0 10px #000000"});
		setTimeout(function(){
			$('#'+id).css({"box-shadow":"0 0 0px #FFF"});
			eval(ontap);
		},100,false);
	});
}

function showCard(html,cardTitle){
   var cards = new Array(1);
   cards.index = 0;
   cards[0] = new Card(new cardRenderer(html));
   if ($("#wallet").length > 0) {
       $("#wallet").remove();
   }
   var wallet = new Wallet("wallet", cards, cardTitle);
   wallet.init();
   
}

function cardRenderer(html){
	function render(){
		return html;
	}
	this.render = render;
}

function parseFunction(func,id){
	func=func.replace("~~icon","\"IMG"+id+"\"");
	func=func.replace("~~widget","\""+id+"\"");
	return func;
}

function unicodeToChar(u){
	return "&#"+parseInt(u,16);
}

function testForInstance(id){
	var ids=[];
		$("#widgets").find("div").each(function(){
			ids.push(this.id);
		});
		while (true){
			if (ids.indexOf(id)>-1){
				id=id+"z";
			}else{
				return id;
				break
			}
		}
}

function dynamicWidget(id, displayTitle, icon, action, update, ontap, init){
	this.id = id;
	this.displayTitle = displayTitle;
	this.displayTitleShift = false;
	this.icon = icon;
	this.action = action;
	this.update = update;
	this.ontap = ontap;
	this.init = init;
	this.isImage=false;
	console.log("Creating "+id+" (DYNAMIC)");
	
	if(displayTitle.indexOf("<br>") == -1){
		this.displayTitleShift = true;
	}
	
	function display(){
		id = this.id;
		displayTitle = this.displayTitle;
		dts = this.displayTitleShift;
		icon=this.icon;
		action=this.action;
		ontap=this.ontap;
		update=this.update;
		init=this.init;
		isImage=this.isImage;
		
		$(document).ready(function(){
			id = testForInstance(id);
			this.id = id;
			$('#widgets').append("<div id='"+ id +"' class='widget'></div>");
			$("#"+id).addClass("widgetShort");
			$("#IMG"+id).addClass("widgetIMGshort");
			if(icon!=="NONE"){
				if(icon.substr(0, 4) == "FILE"){
					var imgData="<img id='IMG"+ id +"' alt='"+ id +"' src='"+icon.substr(4,icon.length)+"'/>";
					isImage = true;
				}else if(icon.substr(0, 4) == "ICON"){
					$("#"+id).css({
						"font-family":"\'icons\'",
						"font-size":"27px"
					});
					var imgData="<div id='IMG"+ id +"'>"+unicodeToChar(icon.substr(4,icon.length))+"</div>";
 				}else if(icon.substr(0, 4) == "TEXT"){
 					if(icon.length !== 4){
 						var imgData="<div id='IMG"+ id +"'>"+icon.substr(4,icon.length)+"</div>";
 					}else{
 						var imgData="<div id='IMG"+ id +"'></div>";
 					}
				}
				var imgid="IMG"+id;
			}else{
				var imgData="";
				var imgid="NoIMGInWidget";
			}
			$("#"+id).html(imgData);
			$("#"+imgid).addClass("widgetIMGshort");
			if(isImage){
				heightOfIMG = $("#"+imgid).height();
				$("#"+imgid).css({
					"float":"left",
					"margin-top":"-"+(heightOfIMG/2)+"px",
					"position":"relative",
					"left":"1px",
					"top":"50%"
				});
			}
			$('#'+id).css({
				backgroundColor:"#397350",
				borderRadius:"25px",
				height:"50px",
				marginLeft:"1px"
			});
			this.isImage = isImage;
			setFunctions(id,displayTitle,imgid,action,update,ontap,dts);
			eval(parseFunction(init,id));
			console.log("Displayed And Set Up "+id);
		});
	}	
	this.display = display;
}
function staticWidget(id, displayTitle, icon, ontap, init){
	this.id = id;
	this.displayTitle = displayTitle;
	this.displayTitleShift = false;
	this.icon = icon;
	this.ontap = ontap;
	this.init = init;
	this.isImage=false;
	console.log("Creating "+id+" (STATIC)");
	
	if(displayTitle.indexOf("<br>") == -1){
		this.displayTitleShift = true;
	}
	
	function display(){
		id = this.id;
		displayTitle = this.displayTitle;
		dts = this.displayTitleShift;
		icon=this.icon;
		update=this.update;
		init=this.init;
		isImage=this.isImage;
		
		$(document).ready(function(){
			id = testForInstance(id);
			this.id = id;
			$('#widgets').append("<div id='"+ id +"' class='widget'></div>");
			$("#"+id).addClass("widgetShort");
			if(icon!=="NONE"){
				if(icon.substr(0, 4) == "FILE"){
					var imgData="<img id='IMG"+ id +"' alt='"+ id +"' src='"+icon.substr(4,icon.length)+"'/>";
					isImage = true;
				}else if(icon.substr(0, 4) == "ICON"){
					$("#"+id).css({
						"font-family":"\'icons\'",
						"font-size":"27px"
					});
					var imgData="<div id='IMG"+ id +"'>"+unicodeToChar(icon.substr(4,icon.length))+"</div>";
 				}else if(icon.substr(0, 4) == "TEXT"){
 					if(icon.length !== 4){
 						var imgData="<div id='IMG"+ id +"'>"+icon.substr(4,icon.length)+"</div>";
 					}else{
 						var imgData="<div id='IMG"+ id +"'></div>";
 					}
				}
				var imgid="IMG"+id;
			}else{
				var imgData="";
				var imgid="NoIMGInWidget";
			}
			$("#"+id).html(imgData);
			$("#"+imgid).addClass("widgetIMGshort");
			if(isImage){
				heightOfIMG = $("#"+imgid).height();
				$("#"+imgid).css({
					"float":"left",
					"margin-top":"-"+(heightOfIMG/2)+"px",
					"position":"relative",
					"left":"1px",
					"top":"50%"
				});
			}
			$('#'+id).css({
				backgroundColor:"#397350",
				borderRadius:"25px",
				height:"50px",
				marginLeft:"1px"
			});
			this.isImage = isImage;
			setFunctions(id,displayTitle,imgid,null,0,ontap,dts);
			eval(parseFunction(init,id));
			console.log("Displayed And Set Up "+id);
		});
	}	
	this.display = display;
}

// Varibles Ready To Use In Handler Functions:
// ~~widget -> ID of widget
// ~~icon  -> ID of icon

// TO CREATE A WIDGET:
// sample = new staticWidget|dynamicWidget( title of widget, 
// location of icon or 'none', 
// (the handler function for the widget), 
// (the amount of time beteen calls of the 'action' function), 
// function to exucute on tap or 'none',
// inition Function )
// sample.display()
